//
//  LocManager.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/12/8.
//

import Foundation
import CoreLocation
import Alamofire

class LocManager: NSObject {
    
    static let shared = LocManager()
    
    /// 获取最新定位信息
    open var didUpdateLocWith:((_ longitude: String, _ latitude: String, _ address: String) -> ())?

    //初始化
    override init() {
        super.init()
        self.setup()
    }
    
    deinit {
        self.lm?.stopUpdatingLocation()
        self.lm?.delegate = nil
        self.lm = nil
    }
    
    // MARK: - lazy load
    /// 定位对象
    private lazy var lm: CLLocationManager? = nil
}

// MARK: -
extension LocManager {
    
    /// 定位初始化
    private func setup(){
        // 定位对象
        self.lm = CLLocationManager.init()
        weak var weakSelf = self
        self.lm?.delegate = weakSelf
        self.lm?.desiredAccuracy = kCLLocationAccuracyBest
        self.lm?.distanceFilter = 200.0
    }
    
    /// 权限检测
    private func locationPermissionsCheck() {
        if CLLocationManager.locationServicesEnabled() == false {
            print("请确认已开启定位服务")
            return
        }
        
        // 请求用户授权
        if #available(iOS 14.0, *) {
            if self.lm?.authorizationStatus == .notDetermined {
                self.lm?.requestWhenInUseAuthorization()
            }
        } else {
            // Fallback on earlier versions
            if CLLocationManager.authorizationStatus() == .notDetermined {
                self.lm?.requestWhenInUseAuthorization()
            }
        }
    }

    /// 开启定位
    func startLoaction() {
        // 已开启定位服务
        if CLLocationManager.locationServicesEnabled() {
            // 是否有授权本App获取定位
            var _auth: CLAuthorizationStatus?
            if #available(iOS 14.0, *) {
                _auth = self.lm?.authorizationStatus
            } else {
                // Fallback on earlier versions
                _auth = CLLocationManager.authorizationStatus()
            }
            
            if _auth == nil || _auth == .denied || _auth == .restricted {
                print("请确认已开启定位服务")
                return
            } else if _auth == .notDetermined {
                self.lm?.requestWhenInUseAuthorization()
            }
            
            //可以定位
            self.lm?.startUpdatingLocation()
        }
        else{
            self.locationPermissionsCheck()
        }
    }
}

//MARK: - CLLocationManagerDelegate
extension LocManager : CLLocationManagerDelegate {
    
    /// 定位失败
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("定位失败：\(error.localizedDescription)")
        Utils.app.window?.showToast(witMsg: "定位失败：\(error.localizedDescription)")
    }
    
    /// 定位成功
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("定位成功")
        
        if let _location = locations.last {
            print("_location: longitude", _location.coordinate.longitude, "_location: latitude", _location.coordinate.latitude)
            
            let geo = CLGeocoder()
            geo.reverseGeocodeLocation(_location) { place, error in
                var address = ""
                let adds : [String] = place?.last?.addressDictionary?["FormattedAddressLines"] as? [String] ?? []
                for add in adds {
                    address.append(add)
                }
                self.didUpdateLocWith?("\(_location.coordinate.longitude)", "\(_location.coordinate.latitude)", address)
            }
            
//            let loc = "\(_location.coordinate.longitude),\(_location.coordinate.latitude)"
//            getAddress(withLocation: loc) { address in
//                if address != "" {
//                    self.didUpdateLocWith?("\(_location.coordinate.longitude)", "\(_location.coordinate.latitude)", address)
//                } else {
//                    let geo = CLGeocoder()
//                    geo.reverseGeocodeLocation(_location) { place, error in
//                        var address = ""
//                        let adds : [String] = place?.last?.addressDictionary?["FormattedAddressLines"] as? [String] ?? []
//                        for add in adds {
//                            address.append(add)
//                        }
//                        self.didUpdateLocWith?("\(_location.coordinate.longitude)", "\(_location.coordinate.latitude)", address)
//                    }
//                }
//            }
            // 关闭定位
            self.lm?.stopUpdatingLocation()
        } else{
            print("请稍后重试")
        }
    }
    
//    func getAddress(withLocation location: String, block: @escaping (_ address: String) -> ()) {
//        let AMAP_API_KEY = "18ea7a28dfd99c7923822a0bdd080611";
//        let AMAP_URL = "https://restapi.amap.com/v3/geocode/regeo?output=json&key=\(AMAP_API_KEY)&location=\(location)";
//        
//        guard let gaodeUrl = URL(string: AMAP_URL) else {
//            block("")
//            return
//        }
//        
//        AF.request(gaodeUrl, method: .get).responseString { string in
//            let jsonData = string.value?.data(using: String.Encoding.utf8, allowLossyConversion: false)
//            guard let resp = try? JSONSerialization.jsonObject(with: jsonData ?? Data(), options: .mutableContainers) else {
//                block("")
//                return
//            }
//            
//            let respData = resp as? [String : Any]
//
//            if let regeocode = respData?["regeocode"] as? [String : Any] {
//                if let fmt_address = regeocode["formatted_address"] as? String {
//                    print("formatted_address", fmt_address)
//                    block(fmt_address)
//                    return
//                }
//                
//                if let addressComponent = regeocode["addressComponent"] as? [String : Any] {
//                    var address = ""
//                    if let province = addressComponent["province"] as? String {
//                        address.append(province)
//                    }
//                    if let district = addressComponent["district"] as? String {
//                        address.append(district)
//                    }
//                    if let township = addressComponent["township"] as? String {
//                        address.append(township)
//                    }
//                    print("address", address)
//                    block(address)
//                    return
//                }
//            }
//            block("")
//        }
//    }
}
